package com.hzit.order.controller;


import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;

import com.hzit.common.utils.PayAsyncVo;
import com.hzit.common.utils.R;
import com.hzit.common.utils.TbPayLog;
import com.hzit.order.entity.Cart;
import com.hzit.order.entity.TbAddress;
import com.hzit.order.entity.TbOrder;
import com.hzit.order.interceptor.LoginInterceptor;
import com.hzit.order.service.AddressService;
import com.hzit.order.service.OrderService;
import com.hzit.order.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.print.DocFlavor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Controller
public class OrderController {
	@Autowired
	private AddressService addressService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private PayService payService;
	//1. 默认欢迎页面
	@GetMapping({"/","/getOrderInfo.html"})
	public String index(Model model){
		//1.1 得到当前登录用户名
		// String name = (String) session.getAttribute("name");
		// if(StrUtil.isBlank(name)){      // 如果用户名不存在就登录
		// 	return "redirect:http://auth.hzit.com/gitee/login?returnUrl=http://order.hzit.com";
		// }
		//1.1 从本地线程得到用户名
		String name = LoginInterceptor.loginName.get();
		System.out.println("name = " + name);
		//1.2 根据用户名查询地址列表
		List<TbAddress> addressList = addressService.findAddresListByName(name);
		//1.3 将用户对应的地址列表放到model中
		model.addAttribute("addressList",addressList);
		//1.4 查询出购物车列表
		List<Cart> cartList = orderService.findCartList(name);
		//1.5 放到model中
		model.addAttribute("cartList",cartList);

		return "getOrderInfo";
	}

	//2. 添加订单
	@PostMapping("/order/add")
	public String add(TbOrder order, HttpSession session,Model model){
		//2.1 得到当前登录用户名
		String name = (String) session.getAttribute("name");
		//2.2 添加到订单
		orderService.add(name,order);
		//2.3 得到支付日志对象
		TbPayLog payLog = orderService.getPayLogByName(name);
		//2.4 将支付日志放到model中
		model.addAttribute("payLog",payLog);
		return "pay";
	}

	//3. 生成支付订单页面
	@GetMapping("/order/createPayPage")
	@ResponseBody
	public String createPayPage(String outTradeNo,String totalFee,HttpSession session) throws AlipayApiException {
		//3.1 得到当前登录用户名
		String name = (String) session.getAttribute("name");
		//3.2  得到支付日志对象
		TbPayLog payLog = orderService.getPayLogByName(name);
		//3.3 将标题及订单号、总金额一并传入页面，生成页面时会用到
		String result = payService.createPayPage(outTradeNo,totalFee,payLog.getSubject());

		System.out.println("result = " + result);
		return result;
	}

	//4. 订单同步回调
	//功能：就示显示当前登录用户的订单列表
	@GetMapping("/order/payed/returnUrl")
	public String payedReturnUrl(HttpSession session,Model model){
		//4.1 得到当前登录的用户名
		String name = (String) session.getAttribute("name");
		//4.2 根据用户名查询订单及订单项列表
		List<TbOrder> orderList = orderService.findOrderListByName(name);
		//4.3 将订单及订单项列表放到model中
		model.addAttribute("orderList",orderList);
		return "orderlist";

	}

	//5. 异步回调: 支付宝后台发来的请求
	//功能：确定是否支付成功，并且发回一组响应数据
	@PostMapping("/order/payed/notifyUrl")
	@ResponseBody
	public String payedNotifyUrl(PayAsyncVo vo, HttpServletRequest request) throws AlipayApiException {
		//5.1 在支付宝为我们发送异步通知前，必须验签通过
		Map<String,String> params = new HashMap<String,String>();
		//5.2 取得表单中所有数据,u将表单中的数据转换为Map<String,String>
		Map<String,String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		//5.3 异步回调：当验签通过时：① 修改支付日志 ② 修改订单状态
		String result = payService.notifyCallBack(params,vo);
		System.out.println("result = " + result);
		//5.4 返回
		return result;

	}

	//3. 只保存tb_order表一张表的数据
	@PostMapping("/order/save")
	@ResponseBody
	public R saveOrder(){
		orderService.saveOrder();
		return R.ok();
	}

	@GetMapping("/order/welcome")
	@ResponseBody
	public String welcome(){
		String name = LoginInterceptor.loginName.get();
		System.out.println("name = " + name);
		return name + ",欢迎你！";
	}
}
